package cn.tedu.sk.finance.income.webapi.repository.impl;


import cn.tedu.cgb2202.sk.pojo.vo.IncomeSimpleVO;
import cn.tedu.sk.finance.income.webapi.repository.IncomeRedisRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Repository;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Repository
public class IncomeRedisRepositoryImpl implements IncomeRedisRepository {

    @Autowired(required = false)
    private RedisTemplate<String, Serializable> redisTemplate;

    @Override
    public Boolean exists(Long id) {
        String key = KEY_INCOME_ITEM_PREFIX + id;
        return redisTemplate.hasKey(key);
    }

    @Override
    public void saveEmptyValue(Long id) {
        String key = KEY_INCOME_ITEM_PREFIX + id;
        redisTemplate.opsForValue().set(key, null, 30, TimeUnit.SECONDS);
    }

    @Override
    public void save(IncomeSimpleVO income) {
        String key = KEY_INCOME_ITEM_PREFIX + income.getId();
        redisTemplate.opsForValue().set(key, income);
    }

    @Override
    public void save(List<IncomeSimpleVO> incomes) {
        for (IncomeSimpleVO income : incomes) {
            redisTemplate.opsForList().rightPush(KEY_INCOME_LIST, income);
        }
    }

    @Override
    public void deleteAllItem() {
        Set<String> keys = redisTemplate.keys(KEY_INCOME_ITEM_PREFIX + "*");
        redisTemplate.delete(keys);
    }

    @Override
    public Boolean deleteList() {
        return redisTemplate.delete(KEY_INCOME_LIST);
    }

    @Override
    public IncomeSimpleVO getIncomelsById(Long id) {
        String key = KEY_INCOME_ITEM_PREFIX + id;
        Serializable result = redisTemplate.opsForValue().get(key);
        if (result == null) {
            return null;
        } else {
            IncomeSimpleVO income = (IncomeSimpleVO) result;
            return income;
        }
    }

    @Override
    public List<IncomeSimpleVO> getIncomeList() {
        List<IncomeSimpleVO> list = new ArrayList<>();
        List<Serializable> range = redisTemplate.opsForList().range(KEY_INCOME_LIST, 0, -1);
        for (Serializable serializable : range) {
            IncomeSimpleVO incomeSimpleVO = (IncomeSimpleVO) serializable;
            list.add(incomeSimpleVO);
        }
        return list;
    }
}
